package com.jingogo.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingogo.common.BusinessException;
import com.jingogo.entity.User;
import com.jingogo.mapper.UserMapper;
import com.jingogo.service.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Slf4j
@Service
public class WalletServiceImpl implements WalletService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void recharge(Long userId, BigDecimal amount, String payMethod) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        user.setWalletBalance(user.getWalletBalance().add(amount));
        userMapper.updateById(user);
    }

    @Override
    public void withdraw(Long userId, BigDecimal amount, String bankCardNumber) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (user.getWalletBalance().compareTo(amount) < 0) {
            throw new BusinessException("余额不足");
        }
        user.setWalletBalance(user.getWalletBalance().subtract(amount));
        userMapper.updateById(user);
    }

    @Override
    public void transfer(Long fromUserId, Long toUserId, BigDecimal amount, String remark) {
        User fromUser = userMapper.selectById(fromUserId);
        User toUser = userMapper.selectById(toUserId);
        if (fromUser == null || toUser == null) {
            throw new BusinessException("用户不存在");
        }
        if (fromUser.getWalletBalance().compareTo(amount) < 0) {
            throw new BusinessException("余额不足");
        }
        fromUser.setWalletBalance(fromUser.getWalletBalance().subtract(amount));
        toUser.setWalletBalance(toUser.getWalletBalance().add(amount));
        userMapper.updateById(fromUser);
        userMapper.updateById(toUser);
    }

    @Override
    public BigDecimal getBalance(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        return user.getWalletBalance();
    }

    @Override
    public IPage<?> getTransactionRecord(Long userId, Integer pageNum, Integer pageSize) {
        // 实现交易记录查询逻辑，这里简单返回空分页
        return new Page<>();
    }
}
